<template>
  <div class="content">
    <div class="pageSearchViewStock">
      <div class="pageTableMenuViewStock">
        <div class="pageTableTitle">
          <div>仓库/库区信息</div>
        </div>
        <div class="pageTableButViewStock">
          <el-button type="primary" :icon="Plus" @click="handleAdd()">新建仓库</el-button>
        </div>
      </div>


      <el-tree :data="wareData" node-key="id" default-expand-all :expand-on-click-node="false"
               :props="{ children: 'sonList' }" :disable-branch-nodes="true" @current-change="handleSearch">
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span :class="data.id == rowInfo.id ? 'is-penultimate' : ''">{{ data.name }}</span>
            <span>
              <el-button type="text" @click="addWare(data)" :icon="Plus" v-if="node.level === 1"></el-button>
              <el-button type="text" @click="append(data, node.level)" :icon="Edit"></el-button>
              <el-button link @click="remove(data)" type="danger" :icon="Delete"></el-button>
            </span>
          </div>
        </template>
      </el-tree>
    </div>

    <div class="pageTableView" style="margin-top: 0">
      <div class="pageTableMenuViewStock">
        <div class="pageTableTitle">
          <div>库位信息</div>
        </div>
        <div class="pageTableButViewStock">
          <el-button type="primary" :icon="Plus" @click="handleAddStock()">新建库位</el-button>
          <el-button type="primary" @click="printClick" :disabled="multipleSelection.length == 0">库位码打印</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="storageList" @selection-change="handleSelectionChange"
                height="calc(100vh - 225px)">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 -->
            {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="库位名称" align="center" min-width="150"/>
        <el-table-column prop="code" label="库位编码" align="center" min-width="150"/>
        <el-table-column prop="typeName" label="库位类型" align="center" min-width="150"/>
        <el-table-column prop="storageBaseName" label="所属仓位名称" align="center" min-width="150"/>
        <el-table-column prop="storageBaseCode" label="所属仓位编码" align="center" min-width="150"/>
        <el-table-column prop="capacity" label="自身容量" align="center" min-width="150"/>
        <el-table-column prop="activate" label="是否冻结" align="center" min-width="150">
          <template #default="scope">
            <div v-if="scope.row.activate">是</div>
            <div v-else>否</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template #default="scope">
            <el-button type="text" @click="handleStockEdit(scope.row)" size="small" :icon="Edit">编辑</el-button>
            <el-button link @click="handleStockDel(scope.row)" type="danger" size="small" :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background :current-page="pageSearch.current" :page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 500]" layout="total, sizes, prev, pager, next" :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>

    <!-- 库位弹窗 -->
    <el-dialog v-model="showStockCrud" :title="crudStockTitle + '库位'">
      <el-form :model="formStockData" ref="ruleStockFormRef" :rules="stockRules" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="所属仓位" required prop="storageBaseId">
              <el-tree-select v-model="formStockData.storageBaseId" :data="wareData"
                              :props="{ children: 'sonList', label: 'name', value: 'id' }" style="width: 300px"
                              @node-click="handleNodeClick"/>
              <!--              <el-select v-model="formStockData.warehouseId" placeholder="选择所属仓位" clearable style="width: 300px">-->
              <!--                <el-option v-for="(item,index) of wareData" :key="item.id"-->
              <!--                           :value="item.id" :label="item.warehouseName">-->
              <!--                  <span style="float: left">{{ item.warehouseName }}</span>-->
              <!--                  <span-->
              <!--                      style="-->
              <!--          float: right;-->
              <!--          color: var(&#45;&#45;el-text-color-secondary);-->
              <!--          font-size: 13px;-->
              <!--        "-->
              <!--                  >-->
              <!--        {{ item.warehouseCode }}-->
              <!--      </span>-->
              <!--                </el-option>-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位编码" required prop="code">
              <el-input v-model="formStockData.code" placeholder="请输入库位编码" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位名称" required prop="name">
              <el-input v-model="formStockData.name" placeholder="请输入库位名称" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自身容量" required prop="capacity">
              <el-input-number v-model="formStockData.capacity" :min="0"/>

            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="库位类型" required prop="storageType">-->
          <!--              <el-input v-model="formStockData.storageType" placeholder="请输入库位类型" style="width: 300px"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="虚拟储位" required prop="isVirtual">
              <el-select v-model="formStockData.isVirtual" placeholder="是否为虚拟储位" clearable style="width: 300px">
                <el-option label="是" :value="true"/>
                <el-option label="否" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 添加批量创建开关 -->
          <!--          <el-col :span="12" v-if="!isStockEdit">-->
          <!--            <el-form-item label="批量创建" prop="batchCreate">-->
          <!--              <el-switch v-model="formStockData.batchCreate" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!-- 添加批量数量输入 -->
          <el-col :span="12" v-if="formStockData.batchCreate && !isStockEdit">
            <el-form-item
                label="批量数量"
                prop="batchCount"
                :rules="[{ required: true, message: '请输入数量', trigger: 'blur' },
              { type: 'number', min: 1, message: '至少创建1个', trigger: 'blur' }]">
              <el-input
                  v-model.number="formStockData.batchCount"
                  type="number"
                  min="1"
                  placeholder="请输入创建数量"
                  style="width: 300px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showStockCrud = false">取消</el-button>
          <el-button type="primary" @click="handleStockSave(ruleStockFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 仓位弹窗 -->
    <el-dialog v-model="showCrud" :title="crudTitle + wareLabel">
      <el-form :model="formData" ref="ruleFormRef" :rules="rules" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="12" v-if="wareLabel == '仓位'">
            <el-form-item label="上级仓库" required prop="parentId">
              <el-select v-model="formData.parentId" placeholder="请选择上级仓库" style="width: 300px">
                <el-option v-for="(item, index) of wareDataAll" :key="item.id" :value="item.id"
                           :label="item.name">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        ">
                    {{ item.code }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="wareLabel + '名称'" required prop="name">
              <el-input v-model="formData.name" :placeholder="'请输入' + wareLabel + '名称'" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="wareLabel + '编码'" required prop="code">
              <el-input v-model="formData.code" :placeholder="'请输入' + wareLabel + '编码'" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item :label="wareLabel + '类型'" required prop="warehouseType">-->
          <!--              <el-input v-model="formData.warehouseType" :placeholder="'请输入' + wareLabel + '类型'" style="width: 300px"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="是否启用" required prop="activate">
              <el-select v-model="formData.activate" placeholder="是否启用" clearable style="width: 300px">
                <el-option label="是" :value="true"/>
                <el-option label="否" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="工厂" required prop="organizationId">-->
          <!--              <el-tree-select v-model="formData.organizationId" filterable :data="workRoomList" check-strictly-->
          <!--                              :props="{ children: 'sonList', label: 'orgName', value: 'id' }" style="width: 300px"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {Delete, Edit, Search, Share, Upload, Refresh, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox, FormInstance, FormRules} from 'element-plus'
import axiosInstance from '@/utils/http/api';
import {getCurrentInstance, reactive, ref} from "vue";
import QRCode from 'qrcode';
import printJS from 'print-js';

onMounted(() => {
  getWeraData()
  getOption();
})
const workRoomList = ref([]); // 车间
// 定义响应式数据
const searchParam = ref({
  user: '',
});

const ruleFormRef = ref<FormInstance>()
const ruleStockFormRef = ref<FormInstance>()

interface RuleForm {
  warehouseName: string
  warehouseCode: string
  storageType: string
  warehouseFrozen: string
}

const rules = reactive<FormRules<formData>>({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入编码', trigger: 'blur'},
  ],
  // warehouseType: [
  //   {required: true, message: '请输入类型', trigger: 'blur'},
  // ],
  activate: [
    {required: true, message: '请选择是否启用', trigger: 'blur'},
  ],
  organizationId: [
    {required: true, message: '请选择工厂/车间', trigger: 'blur'},
  ]
})

const stockRules = reactive<FormRules<formStockData>>({
  code: [
    {required: true, message: "请输入库位编码", trigger: "blur"},
  ],
  storageBaseId: [
    {required: true, message: "请选择所属仓位", trigger: "blur"},
  ],
  name: [
    {required: true, message: "请输入库位名称", trigger: "blur"},
  ],
  isVirtual: [
    {required: true, message: "请选择是否为虚拟储位", trigger: "blur"},
  ],
  capacity: [
    {required: true, message: "请输入自身容量", trigger: "blur"},
  ],
})


const formData = ref({})
const wareLabel = ref('')
const formStockData = ref({})

const pageTotal = ref(null)

const isEdit = ref(false)//是否编辑
const showCrud = ref(false)//编辑/新建弹框
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});

const crudStockTitle = computed(() => {
  return isStockEdit.value ? '编辑' : '新建';
});

// 点击保存库位
const handleStockSave = async (e: FormInstance | undefined) => {
  if (!e) return
  await e.validate((valid, fields) => {
    if (valid) {
      if (isStockEdit.value) {
        // 编辑
        formStockData.value.availableTypes = [12, 2]
        formStockData.value.availableTypeIds = [12, 2]
        axiosInstance.put('/api/logistics/storagePosition/update', formStockData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message)
            return false
          }
          ElMessage.success('操作成功!')
          handleSearch(rowInfo.value)
          // handleSearch(); // 刷新数据
        })
      } else {
        if (formStockData.value.batchCreate) {
          if (!formStockData.value.batchCount || formStockData.value.batchCount == 0 || formStockData.value.batchCount == '') {
            ElMessage.error('请输入批量数量')
            return false
          }
          const batchParam = []
          for (let i = 0; i < formStockData.value.batchCount; i++) {
            const param = {
              ...formStockData.value,
              storageCode: formStockData.value.storageCode + (Number(i) + 1),
              storageName: formStockData.value.storageName + (Number(i) + 1)
            }
            batchParam.push(param)
          }

          axiosInstance.put('/api/logistics/storagePosition/update', batchParam).then(res => {
            if (res.code != 200) {
              ElMessage.error(res.message)
              return false
            }
            ElMessage.success('操作成功!')
            handleSearch(rowInfo.value)
          })
        } else {
          formStockData.value.availableTypes = [12, 2]
          formStockData.value.availableTypeIds = [12, 2]


          axiosInstance.post('/api/logistics/storagePosition/save', formStockData.value).then(res => {
            if (res.code != 200) {
              ElMessage.error(res.message)
              return false
            }
            ElMessage.success('操作成功!')
            handleSearch(rowInfo.value)
          })
        }
        // 新建

      }

    }
  })
}

// 点击保存库位
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return
  await e.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/logistics/storageBase/update', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message)
            return false
          }
          ElMessage.success('操作成功!')
          getWeraData()
          // handleSearch(); // 刷新数据
        })
      } else {
        // 新建
        axiosInstance.post('/api/logistics/storageBase/save', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message)
            return false
          }
          ElMessage.success('操作成功!')
          getWeraData()
          // handleSearch(); // 刷新数据
        })
      }

    }
  })
}
// 点击新建仓库
const handleAdd = () => {
  wareLabel.value = '仓库'
  isEdit.value = false
  formData.value = {
    parentId: '0'
  }
  showCrud.value = true
}

// 新建仓位
const addWare = (e) => {
  console.log(e)
  isEdit.value = false

  wareLabel.value = '仓位'
  formData.value = {
    parentId: e.id
  }
  showCrud.value = true
}
// 点击编辑仓库
const append = (e, i) => {
  if (i === 1) {
    wareLabel.value = '仓库'
  } else {
    wareLabel.value = '仓位'
  }
  isEdit.value = true
  formData.value = JSON.parse(JSON.stringify(e))
  showCrud.value = true
}
const isStockEdit = ref(false)
const showStockCrud = ref(false)

// 点击新建库位
const handleAddStock = () => {
  isStockEdit.value = false
  formStockData.value = {}
  formStockData.value.storageBaseId = rowInfo.value.id
  showStockCrud.value = true
}

// 仓位列表
const wareData = ref([])

const paginatedData = ref([])


const pageSearch = ref({
  current: 1,
  pageSize: 10
})

const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};


const rowInfo = ref({})
const storageList = ref([])
const handleSearch = (row) => {
  let param = {}
  rowInfo.value = row
  param = {storageBaseId: row.id}
  axiosInstance.get("/api/logistics/storagePosition/getStoragePositionWithBaseId", {params: param})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false
        }
        storageList.value = res.data
        pageTotal.value = res.data.total
        showStockCrud.value = false
      })

}

const wareDataAll = ref([])


const getWeraData = () => {
  axiosInstance.post('/api/logistics/storageBase/getAll', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false
    }
    const flatData = JSON.parse(JSON.stringify(res.data));

    // 构建树形结构
    wareData.value = buildTree(flatData);
    wareDataAll.value = flatData; // 保留原始数据

    showCrud.value = false;
    showStockCrud.value = false;
    handleSearch(res.data[0])
  });
}

const buildTree = (items, parentId = '0') => {
  // 边界检查
  if (!Array.isArray(items) || items.length === 0) return [];

  // 使用Map优化查找性能
  const nodeMap = new Map();
  const tree = [];

  // 第一次遍历：建立节点映射
  items.forEach(item => {
    // 处理不存在parentId的情况
    if (item.parentId === undefined || item.parentId === null) {
      item.parentId = '0';
    }
    nodeMap.set(item.id, {...item, sonList: []});
  });

  // 第二次遍历：构建树结构
  nodeMap.forEach(node => {
    const parent = nodeMap.get(node.parentId);
    if (parent && node.parentId !== parentId) {
      parent.sonList.push(node);
    } else if (node.parentId === parentId) {
      tree.push(node);
    }
  });

  return tree;
};

const handleEdit = (e) => {
  formData.value = e
  isEdit.value = true
  showCrud.value = true
}


const handleStockEdit = (e) => {
  formStockData.value = e
  isStockEdit.value = true
  showStockCrud.value = true
}

const customNodeClass = (data: Tree, node: Node) => {
  return 'is-penultimate'
}

const handleNodeClick = (node, nodeComponent) => {
  console.log(node)
  // 如果是第一级节点，不进行任何操作
  if (node.level === 1) {
    return;
  }
  // 否则，更新 v-model
  formStockData.value.warehouseId = node.id;
}

const handleStockDel = (e) => {
  ElMessageBox.confirm(
      '确认删除该库位?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        axiosInstance.delete(`/api/logistics/storagePosition/delete`, {
          data: {
            ids: [e.id]
          }
        })
            .then(res => {
              if (res.code === 200) {
                ElMessage.success("删除成功");
                handleSearch(rowInfo.value)
              }
            });
      })
}


const remove = (e) => {
  ElMessageBox.confirm(
      '确认删除该仓位?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        axiosInstance.delete(`/api/basedataWarehouse/delete`, {
          data: {
            ids: [e.id]
          }
        })
            .then(res => {
              if (res.code === 200) {
                ElMessage.success("删除成功");
                getWeraData();
              }
            });
      })
}

const handleDel = (e) => {
  ElMessageBox.confirm(
      '是否确认删除?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
}

const {proxy}: any = getCurrentInstance();


// 打印
const printClick = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一个库位');
    return;
  }

  try {
    // 创建打印窗口
    const printWindow = window.open('', '_blank');

    // 生成打印内容
    let printContent = `
      <html>
        <head>
          <title>库位码打印</title>
          <style>
                 @page { size: auto; margin: 0; }
        body { margin: 5mm; font-family: Arial; }
        .print-item {
          display: flex;
          align-items: center;
          margin-bottom: 5mm;
          page-break-after: always;
        }
        .qrcode {
          margin-right: 10mm;
          flex-shrink: 0;
        }
        .info {
          font-size: 16pt;
          flex-grow: 1;
        }
        .info p {
          margin: 3px 0;
          line-height: 1.2;
        }
          </style>
        </head>
        <body>
    `;

    // 为每个选中的库位生成打印内容
    for (const item of multipleSelection.value) {
      const qrcodeUrl = await QRCode.toDataURL(item.code, {width: 150});
      printContent += `
<div class="print-item">
          <div class="qrcode">
            <img src="${qrcodeUrl}" style="width:150px;height:150px;">
          </div>
          <div class="info">
            <p><strong>库位名称:</strong> ${item.name || ''}</p>
            <p><strong>库位编码:</strong> ${item.code || ''}</p>
            <p><strong>所属仓位名称:</strong> ${item.storageBaseName || ''}</p>
            <p><strong>所属仓位编码:</strong> ${item.storageBaseCode || ''}</p>
          </div>
        </div>
      `
    }

    printContent += `
  <script>
    window.onload = function() {
      setTimeout(() => {
        window.print();
        window.close();
      }, 300);
    }
  <` + `/script>
</body>
</html>`;

    printWindow.document.write(printContent);
    printWindow.document.close();

  } catch (error) {
    console.error('打印出错:', error);
    ElMessage.error('生成打印内容失败');
  }
};

// 搜索 检索 点击搜索
const getSearch = () => {

};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e
  handleSearch(rowInfo.value)
}

const handleCurrentChange = (e) => {
  pageSearch.value.current = e
  handleSearch(rowInfo.value)
}

const getOption = () => {
// axiosInstance.post('/api/basedataOrganization/getAll', {})
//     .then(res => {
//       if (res.code !== 200) {
//         ElMessage.error(res.message);
//         return false;
//       }
//       workRoomList.value = res.data;
//     });
};

</script>
<style scoped lang="scss">
.content {
  background: #f9f9f9;
  height: calc(100vh - 105px);
  display: flex;
}

.pageSearchViewStock {
  width: 25%;
  padding: 20px;
  background: #fff;
  border-right: 1px solid #f9f9f9;
}

.pageTableView {
  width: 75%;
  background: #fff;
  border-radius: 10px;
}

.pageTableMenuViewStock {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.pageTableTitleStock {
  font-size: 18px;
}

.pageTableClass {
  width: 100%;
  height: 100%;
  margin: 10px 0;
}

.pagePagination {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.is-penultimate {
  color: #626aef;
  font-weight: 700;
}
</style>
